(function ($, _, amplify, window, document) {
    'use strict';

    var rootElem,
        bookshelf,
        editor,
        fadeTime = 300;

    $(document).ready(function () {
        rootElem = $('#natext .bookshelf');
        bookshelf = new Bookshelf(rootElem, $);
        editor = new BookshelfEditor(rootElem, $, amplify);

        bookshelf.on('addBook', function () {
            amplify.publish('addNewBook');
        });

        bookshelf.on('editBook', function (postID) {
            amplify.publish('editBook', {post_id: postID});
        });

        bookshelf.on('removeBook', function (item, postID) {
            amplify.publish('removeBook', {'item': item, 'post_id': postID});
        });

        editor.on('cancel', function () {
            amplify.publish('cancelUpdates');
        });

        editor.on('saveBook', function () {
            amplify.publish('bookSaved');
        });

        editor.on('updateBook', function (postID) {
            amplify.publish('bookUpdated', {'post_id': postID});
        });
    });


    // Subscriptions
    // ------------------------------
    amplify.subscribe('addNewBook', __addNewBook);
    amplify.subscribe('bookAdded', __updateBookshelf);
    amplify.subscribe('editBook', __editBook);
    amplify.subscribe('bookUpdated', __updateBookshelf);
    amplify.subscribe('bookSaved', __updateBookshelf);
    amplify.subscribe('removeBook', __removeBook);
    amplify.subscribe('cancelUpdates', __cancelUpdates);

    function __showEditor() {
        bookshelf.hide();
        editor.show();
    }

    function __hideEditor() {
        editor.hide();
        bookshelf.show();
    }

    function __addNewBook() {
        editor.reset();
        editor.setMode('add');
        editor.setPostId('');
        __showEditor();
    }

    function __editBook(data) {
        editor.setMode('edit');
        editor.setPostId(data.post_id);
        editor.loadData(data.post_id, __showEditor);
    }

    function __removeBook(data) {
        var sure = confirm('Are you sure you want to remove this book?');

        if (sure) {
            $.post(NatExt.wp.ajax_url, {
                'action' : 'NatExtAjax_Bookshelf_RemoveItems',
                'post_id': data.post_id
            }, function () {
                data.item.hide(300, function () {
                    $(this).remove();
                });
            })

        }
    }

    function __updateBookshelf() {
        var bookshelfItems = $.post(NatExt.wp.ajax_url, {
            'action': 'NatExtAjax_Bookshelf_GetItems'
        }, function (data) {
            bookshelf.update(data);
            __hideEditor();
        });
    }

    function __cancelUpdates() {
        editor.setMode('normal');
        editor.setPostId('');
        __hideEditor();
    }
}(jQuery, _, amplify, window, document));